using Emgu.CV;
using System;

namespace DualCameraApp.Models;

public class VideoRecorder : IDisposable
{
    private VideoWriter _writer;
    private bool _isRecording;
    
    public string FilePath { get; }
    public int FrameWidth { get; }
    public int FrameHeight { get; }
    public double Fps { get; }
    
    public VideoRecorder(string filePath, int frameWidth, int frameHeight, double fps = 30)
    {
        FilePath = filePath;
        FrameWidth = frameWidth;
        FrameHeight = frameHeight;
        Fps = fps;
        
        // int fourcc = VideoWriter.Fourcc('M', 'P', '4', 'V');
        int fourcc = VideoWriter.Fourcc('M', 'J', 'P', 'G');
        // int fourcc = VideoWriter.Fourcc('D', 'I', 'V', 'X');
        filePath = filePath.Replace(".mp4", ".avi");
        _writer = new VideoWriter(filePath, fourcc, fps, new System.Drawing.Size(frameWidth, frameHeight), true);
    }
    
    public void WriteFrame(Mat frame)
    {
        if (_isRecording && _writer != null && !frame.IsEmpty)
        {
            // 调整帧大小以匹配录制器设置
            using var resizedFrame = new Mat();
            if (frame.Width != FrameWidth || frame.Height != FrameHeight)
            {
                CvInvoke.Resize(frame, resizedFrame, new System.Drawing.Size(FrameWidth, FrameHeight));
                _writer.Write(resizedFrame);
            }
            else
            {
                _writer.Write(frame);
            }
        }
    }
    
    public void StartRecording()
    {
        _isRecording = true;
    }
    
    public void StopRecording()
    {
        _isRecording = false;
    }
    
    public void Dispose()
    {
        StopRecording();
        _writer?.Dispose();
        GC.SuppressFinalize(this);
    }
}